package org.example.servlet;

import org.example.dao.UserDao;
import org.example.util.PasswordUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 用户注册Servlet
 */
public class RegisterServlet extends HttpServlet {
    
    private UserDao userDao;
    
    @Override
    public void init() throws ServletException {
        userDao = new UserDao();
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String confirmPassword = request.getParameter("confirmPassword");
        
        PrintWriter out = response.getWriter();
        
        // 参数验证
        if (username == null || username.trim().isEmpty()) {
            out.println("<script>alert('用户名不能为空'); history.back();</script>");
            return;
        }
        
        if (password == null || password.trim().isEmpty()) {
            out.println("<script>alert('密码不能为空'); history.back();</script>");
            return;
        }
        
        if (!password.equals(confirmPassword)) {
            out.println("<script>alert('两次密码输入不一致'); history.back();</script>");
            return;
        }
        
        // 检查用户名是否已存在
        if (userDao.isUsernameExists(username)) {
            out.println("<script>alert('用户名已存在'); history.back();</script>");
            return;
        }
        
        // 加密密码并创建用户
        String hashedPassword = PasswordUtil.hashPassword(password);
        boolean success = userDao.createUser(username, hashedPassword);
        
        if (success) {
            out.println("<script>alert('注册成功'); window.location.href='login.html';</script>");
        } else {
            out.println("<script>alert('注册失败，请重试'); history.back();</script>");
        }
    }
}
